<template>
  <div class="Document-container">
    <div class="Document-top">
      <el-link
        type="info"
        @click="DownLoadDocument"
        :underline="false"
        class="title"
        >{{ currentDocument.document_title }}</el-link
      >
      <span class="create_time">{{
        currentDocument.create_time | formatDate
      }}</span>
    </div>
    <div class="Document-center">
      <span v-html="currentDocument.document_abstract"></span>
    </div>
    <div class="Document-bottom">
      <div class="info-list">
        <span class="view">阅读 {{ currentDocument.view_count }}</span>
        <span class="view">点赞: {{ currentDocument.like_count }}</span>
        <span class="view">评论: {{ currentDocument.comment_count }}</span>
      </div>
      <div class="options" v-if="isEdit">
        <el-button class="CustomBtn" @click="DownLoadDocument">下载</el-button>

        <el-button class="CustomBtn" @click="EditDocument">编辑</el-button>
        <el-button class="CustomBtn" @click="deleteDocument">删除</el-button>
      </div>
      <div></div>
      <EditDialog
        :showEditDialogVisible="showEditDialogVisible"
        :document="document"
        @closeDialog="closeDialog"
      />
    </div>
  </div>
</template>

<script>
import { defineAsyncComponent } from 'vue'
import { downLoadFile } from '@/api/cos'

export default {
  props: {
    document: {
      type: Object,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  components: {
    EditDialog: defineAsyncComponent(() => import('./EditDialog'))
  },
  data() {
    return {
      currentDocument: {},
      showEditDialogVisible: false
    }
  },
  computed: {},
  watch: {
    // 更换props参数到data
    document: {
      immediate: true,
      deep: true,
      handler(val, oldval) {
        this.currentDocument = val
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 浏览功能
    async DownLoadDocument() {
      // cos下载
      const regex = /\/([^/]+)$/
      const match = this.document.document_url.match(regex)

      // 提取匹配结果中的内容
      if (match) {
        const lastSegment = match[1]
        console.log(decodeURIComponent(lastSegment)) // 输出："5%E3%80%81%E6%AF%95%E4%B8%9A%E8%AE%BA%E6%96%87.doc"
        const response = await downLoadFile(
          'file/' + decodeURIComponent(lastSegment)
        )
        console.log(response)
        // 如果获取文件成功
        if (response.statusCode == 200) {
          // 假设下载的数据存储在 response 对象中
          const fileData = response.Body // 或 response.Body，根据实际情况获取文件内容

          // 处理二进制数据
          const blob = new Blob([fileData], {
            type: 'application/octet-stream'
          })

          // 创建临时的 URL
          const url = URL.createObjectURL(blob)

          // 创建一个 <a> 标签用于触发下载
          const link = document.createElement('a')
          link.href = url
          link.download = decodeURIComponent(lastSegment) // 设置下载文件的名称
          link.style.display = 'none'

          // 将 <a> 标签添加到 DOM 中
          document.body.appendChild(link)

          // 触发下载
          link.click()

          // 清理临时的 URL 和 <a> 标签
          URL.revokeObjectURL(url)
          document.body.removeChild(link)
        }
      } else {
        return this.$message.error('文件不存在')
      }
      // 本地下载
      // const res = await this.$API.document.addDownloadNum(this.document.id)
      // if (res.status == 200) {
      //   // Create a temporary anchor element
      //   const link = document.createElement('a');
      //   // Set the href attribute to the document_url
      //   link.href = this.document.document_url;
      //   // Specify that the link should be downloaded when clicked
      //   link.setAttribute('download', '');
      //   // Programmatically click the link to start the download
      //   link.click();
      //   // Clean up by removing the temporary anchor element
      //   link.remove();
      // }
    },
    // 删除功能
    deleteDocument() {
      let formData = new FormData()
      formData.append('document_id', this.document.id)
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$API.document.deleteDocument(formData)
          console.log(res)
          if ((res.status = 200)) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 发送事件
            this.$bus.$emit('DeleteDocumentSuccess')
          } else {
            this.message.error(res.msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleCommand(c) {
      // 子标签选择判断
      switch (c) {
        case 'delete':
          this.deleteDocument()
          break
      }
    },
    // 编辑文档
    EditDocument() {
      this.showEditDialogVisible = true
    },
    // 关闭编辑窗口事件
    closeDialog() {
      this.showEditDialogVisible = false
      this.$emit('ReloadDocumentList')
    }
  }
}
</script>

<style scoped>
.Document-container {
  line-height: 2em;
}
.Document-top {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.title {
  font-size: 16px;
  color: #55596b;
}
.create_time {
  color: #9f9f9c;
}
.Document-center {
  width: 100%;
  color: #9fa2af;
}
.Document-bottom {
  width: 100%;
  display: flex;
  flex-direction: space-between;
}

.info-list {
  width: 50%;
  color: #999aad;
}
.info-list span {
  margin-right: 10px;
}
.options {
  width: 50%;
  display: flex;
  justify-content: right;
}
.options * {
  margin-left: 10px;
}
</style>
